import { action, makeObservable, observable } from 'mobx'
import { cloneDeep } from 'lodash'
import { fetchLogin, fetchUserInfo } from '@/api/system/user'
import { LoginInfo } from '@/interface/login'
import { removeToken, setToken } from '@/utils/auth'

class User {
  constructor() {
    makeObservable(this)
  }

  @observable token = ''

  @observable refreshToken = ''

  @observable menu = []

  @observable userInfo: any = {} // 暂时解决类型报错，待定义类型

  @observable phone = ''

  @action login = async (userInfo: LoginInfo) => {
    try {
      const response = await fetchLogin(userInfo)
      const { token, refreshToken } = response
      this.token = token
      this.refreshToken = refreshToken
      setToken(token)

      sessionStorage.setItem('refreshToken', refreshToken)

      // await this.getUserInfo()

      return Promise.resolve(response)
    } catch (e) {
      return Promise.reject(e)
    }
  }

  @action getUserInfo = async () => {
    try {
      const res = await fetchUserInfo()
      const { menu, activeUsers } = cloneDeep(res)
      this.menu = menu
      this.userInfo = activeUsers

      return Promise.resolve(menu)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  @action getUserData = (userData) => {
    const { menu, activeUsers } = cloneDeep(userData)
    this.menu = menu
    this.userInfo = activeUsers
  }

  @action logout = () => {
    removeToken()
    this.menu = []
    this.userInfo = {}
  }
}

export default new User()
